﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CellarDoor.Gui.Elements
{
    public class UiContainer : UiElement
    {
        private Rectangle childArea;
        /// <summary>
        /// Gets the area that contains all child elements
        /// </summary>
        public Rectangle ChildArea
        {
            get { return childArea; }
        }

        private bool areaIsInvalid;

        /// <summary>
        /// Creates a new ui container
        /// </summary>
        /// <param name="manager"></param>
        public UiContainer()
            : base()
        {
            Initialize();
        }

        /// <summary>
        /// Creates a new ui container
        /// </summary>
        /// <param name="parent"></param>
        public UiContainer(UiElement parent)
            : base(parent)
        {
            Initialize();
        }

        private void Initialize()
        {
            areaIsInvalid = true;
            this.Elements.ControlAdded += Elements_ControlAdded;
            this.Elements.ControlRemoved += Elements_ControlRemoved;
        }

        void Elements_ControlRemoved(object sender, UiElementEventArgs e)
        {
            e.Element.BoundsChanged -= Element_BoundsChanged;
        }

        void Elements_ControlAdded(object sender, UiElementEventArgs e)
        {
            e.Element.BoundsChanged += Element_BoundsChanged;
        }

        void Element_BoundsChanged(object sender, UiEventArgs args)
        {
            areaIsInvalid = true;
        }

        public override void Draw(Vector4 color)
        {
            if (areaIsInvalid)
            {
                childArea.X = 0;
                childArea.Y = 0;
                childArea.Width = 0;
                childArea.Height = 0;

                foreach (UiElement element in Elements)
                {
                    element.Draw(color);
                    childArea = Rectangle.Union(childArea, new Rectangle((int)element.Location.X, (int)element.Location.Y, (int)element.Width, (int)element.Height));
                }

                areaIsInvalid = false;
            }
            base.Draw(color);
        }
    }
}
